<template>
  <div id="panel">
    <el-card class="queryForm">
      <el-form
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        :label-position="'right'"
      >
        <!-- 水源地名称查询 -->
        <el-form-item label="水源地名称：" prop="drinksourceid">
          <el-input
            v-model="queryParams.drinksourceid"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <!-- 巡查时间查询 -->
        <el-form-item label="巡查时间：" prop="patrolTime">
          <el-input
            v-model="queryParams.patrolTime"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <!-- 查询按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleQuery"
            style="padding: 10px"
            >查询</el-button
          >
        </el-form-item>
        <!-- 清除按钮 -->
        <el-form-item>
          <el-button @click="resetQuery" style="padding: 10px">清除</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="pageContent">
      <!-- 功能按钮区 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >添加</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格区 -->
      <el-table
        :data="tableData"
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column prop="drinksourcename" label="水源地名称" />
        <el-table-column prop="inspectiontime" label="巡查时间" />
        <el-table-column prop="inspectionnote" label="描述" />
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
            <el-button type="text" @click="detail(scope.row)">详情</el-button>
            <el-button type="text" @click="delRows(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区（保留） -->
      <el-pagination
        class="pagination-self"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :pager-count="5"
        :current-page="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        layout="slot, total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
      >
        <el-button
          class="refresh-button"
          icon="el-icon-refresh"
          title="刷新"
          @click="getList"
        />
      </el-pagination>
    </el-card>

    <!-- 新增/修改弹出层（核心修改：详情模式与编辑模式界面一致） -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 第一行：水源地名称 + 巡查日期 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="水源地名称" prop="drinksourceid">
              <el-select
                v-model="form.drinksourceid"
                placeholder="请选择水源地"
                style="width: 100%"
                :disabled="title === '查看巡查记录'"
              >
                <el-option
                  v-for="item in qyList"
                  :key="item.id"
                  :label="item.drinksourcename"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡查日期" prop="inspectiontime">
              <el-date-picker
                v-model="form.inspectiontime"
                type="date"
                placeholder="请选择巡查日期"
                style="width: 100%"
                :disabled="title === '查看巡查记录'"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：行政区划 + 详细地址 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="行政区划" prop="countycode">
              <el-select
                v-model="form.countycode"
                placeholder="选择区域"
                style="width: 100%"
                clearable
                :disabled="title === '查看巡查记录'"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入详细地址"
                style="width: 100%"
                :disabled="title === '查看巡查记录'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 巡查描述（文本域） -->
        <el-form-item label="巡查描述" prop="inspectionnote">
          <el-input
            v-model="form.inspectionnote"
            type="textarea"
            rows="4"
            placeholder="请输入巡查描述"
            :disabled="title === '查看巡查记录'"
          ></el-input>
        </el-form-item>

        <!-- 巡查图片（核心修改：详情模式显示上传组件样式，但禁用所有操作） -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="巡查图片">
              <el-upload
                :action="baseUrl + '/common/upload'"
                :headers="headers"
                accept="image/jpeg,image/gif,image/png,image/jpg"
                list-type="picture-card"
                :limit="5"
                :file-list="previewImageList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :disabled="title === '查看巡查记录'"
              >
                <!-- 详情模式隐藏新增图标 -->
                <i class="el-icon-plus" v-if="title !== '查看巡查记录'"></i>
              </el-upload>

              <!-- 上传提示（仅非详情模式显示） -->
              <div
                v-if="title !== '查看巡查记录'"
                style="margin-top: 10px; color: #666; font-size: 12px"
              >
                提示：最多上传5张图片，单张不超过500KB
              </div>

              <!-- 图片预览弹窗（共用） -->
              <el-dialog
                :visible.sync="dialogVisible"
                append-to-body
                width="80%"
                title="图片预览"
              >
                <div class="dialog-img-container">
                  <img
                    width="100%"
                    :src="dialogImageUrl"
                    alt=""
                    class="dialog-img"
                  />
                </div>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 弹出层底部按钮：查看时隐藏保存按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm"
          v-if="title !== '查看巡查记录'"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { getdrinksourcelist } from "../api/baseinfo";
import {
  getPatrolRecordList,
  addPatrolRecord,
  updatePatrolRecord,
  deletePatrolRecord,
  getPatrolRecordDetail,
} from "@/api/drinkingwatersource.js";
import { getRegionList } from "@/api/dataResources/monitorData/region.js";

export default {
  name: "HydrologicStation",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: {},
  computed: {},
  data() {
    return {
      // 表格高度
      tableHeight: window.innerHeight - 400,
      regionList: [],
      qyList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drinksourceid: "", // 水源地名称
        patrolTime: "", // 巡查时间（模糊查询）
      },
      // 表格数据
      tableList: {
        total: 0,
        rows: [],
      },
      tableData: [],
      // 选中数据ID数组
      ids: [],
      // 弹出层控制
      open: false,
      title: "",
      // 表单数据
      form: {
        id: "", // 主键ID（编辑时用）
        drinksourceid: "", // 水源地名称
        inspectiontime: "", // 巡查日期
        countycode: "", // 行政区划
        address: "", // 详细地址
        inspectionnote: "", // 巡查描述
        inspectionimageurl: "", // 图片地址（接口返回：逗号分隔字符串）
      },
      // 图片相关：改造为多图存储
      previewImageList: [], // 图片回显列表（[{url: 完整地址}, ...]）
      photoFile: [], // 上传成功后的文件名数组（用于提交拼接）
      baseUrl: process.env.VUE_APP_BASE_API, // 修正基础地址赋值
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 表单校验规则
      rules: {
        drinksourceid: [
          { required: true, message: "请选择水源地名称", trigger: "change" },
        ],
        inspectiontime: [
          { required: true, message: "请选择巡查日期", trigger: "change" },
        ],
        inspectionnote: [
          { required: true, message: "请输入巡查描述", trigger: "blur" },
          {
            min: 10,
            max: 500,
            message: "描述长度需在10-500字之间",
            trigger: "blur",
          },
        ],
        inspectionimageurl: [
          {
            required: true,
            message: "请至少上传1张巡查图片",
            trigger: "change",
          },
        ],
      },
      // 图片预览相关
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  watch: {},
  created() {
    this.getRegionList();
    this.getQyList();
  },
  mounted() {
    this.pageInit();
  },
  methods: {
    // 页面初始化
    pageInit() {
      this.getList();
    },

    // 获取行政区划列表
    async getRegionList() {
      let res = await getRegionList();
      if (res.code == 200) {
        this.regionList = res.rows;
      }
    },

    // 获取水源地列表
    getQyList() {
      let query = { pageNum: 1, pageSize: 1000 };
      getdrinksourcelist(query).then((response) => {
        this.qyList = response.rows || [];
      });
    },

    // 获取表格数据
    getList() {
      getPatrolRecordList(this.queryParams).then((response) => {
        this.tableData = response.rows || [];
        this.tableList.total = response.total || 0;
      });
    },

    // 表格选择事件
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },

    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡查记录";
    },

    // 编辑按钮操作（行内）- 改造多图回显
    edit(row) {
      this.reset();
      getPatrolRecordDetail(row.id).then((response) => {
        const data = response.data;
        // 处理图片回显：逗号分隔字符串 → 数组 → 拼接完整地址
        const imageUrls = data.inspectionimageurl
          ? data.inspectionimageurl.split(",").filter((url) => url) // 过滤空值
          : [];
        this.previewImageList = imageUrls.map((url) => ({
          url: process.env.VUE_APP_BASE_API + url,
          status: "success", // 标记为已上传状态
          // 存储原始文件名（关键：用于删除时匹配）
          response: { fileName: url },
        }));
        // 存储原始文件名数组（用于提交）
        this.photoFile = [...imageUrls];
        // 同步表单字段（逗号分隔字符串）
        this.form.inspectionimageurl = this.photoFile.join(",");

        // 回显表单数据
        this.form = {
          id: data.id,
          drinksourceid: data.drinksourceid,
          inspectiontime: data.inspectiontime
            ? new Date(data.inspectiontime)
            : "",
          countycode: data.countycode || "",
          address: data.address || "",
          inspectionnote: data.inspectionnote,
          inspectionimageurl: this.photoFile.join(","), // 逗号分隔字符串
        };
        this.open = true;
        this.title = "修改巡查记录";
      });
    },

    // 详情按钮操作 - 核心修改：与编辑模式界面一致，仅禁用所有操作
    detail(row) {
      this.reset();
      getPatrolRecordDetail(row.id).then((response) => {
        const data = response.data;
        // 处理图片回显：逗号分隔字符串 → 数组 → 拼接完整地址（与编辑模式一致）
        const imageUrls = data.inspectionimageurl
          ? data.inspectionimageurl.split(",").filter((url) => url)
          : [];
        this.previewImageList = imageUrls.map((url) => ({
          url: process.env.VUE_APP_BASE_API + url,
          status: "success", // 标记为已上传状态，显示完整样式
          response: { fileName: url }, // 存储原始文件名，保持数据结构一致
        }));
        // 存储原始文件名数组（仅用于回显）
        this.photoFile = [...imageUrls];
        this.form.inspectionimageurl = this.photoFile.join(",");

        // 回显表单数据（与编辑模式完全一致）
        this.form = {
          id: data.id,
          drinksourceid: data.drinksourceid,
          inspectiontime: data.inspectiontime
            ? new Date(data.inspectiontime)
            : "",
          countycode: data.countycode || "",
          address: data.address || "",
          inspectionnote: data.inspectionnote,
          inspectionimageurl: this.photoFile.join(","),
        };
        this.open = true;
        this.title = "查看巡查记录";

        // 详情模式：确保所有表单组件都被禁用（双重保险）
        this.$nextTick(() => {
          const formItems = this.$refs.form.$el.querySelectorAll(
            ".el-select, .el-date-picker, .el-input, .el-textarea, .el-upload"
          );
          formItems.forEach((item) => {
            item.setAttribute("disabled", true);
          });
        });
      });
    },

    // 删除按钮操作（行内）
    delRows(row) {
      this.$confirm("是否确认删除该巡查记录？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePatrolRecord(row.id).then((response) => {
            this.$message.success("删除成功");
            this.getList();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 批量删除（若需）
    handleDelete() {
      if (this.ids.length === 0) {
        this.$message.warning("请选择要删除的数据");
        return;
      }
      this.$confirm("是否确认删除选中的巡查记录？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePatrolRecord(this.ids.join(",")).then((response) => {
            this.$message.success("删除成功");
            this.getList();
            this.ids = [];
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 分页-每页条数改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    // 分页-当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 搜索查询
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置查询条件
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        drinksourceid: "",
        patrolTime: "",
      };
      this.getList();
    },

    // 取消弹出层
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置（改造多图清空）
    reset() {
      this.form = {
        id: "",
        drinksourceid: "",
        inspectiontime: "",
        countycode: "",
        address: "",
        inspectionnote: "",
        inspectionimageurl: "",
      };
      this.previewImageList = []; // 清空图片回显
      this.photoFile = []; // 清空文件名数组
      this.$refs.form && this.$refs.form.resetFields();

      // 重置组件禁用状态
      this.$nextTick(() => {
        const formItems = this.$refs.form?.$el.querySelectorAll(
          ".el-select, .el-date-picker, .el-input, .el-upload, .el-textarea"
        );
        formItems &&
          formItems.forEach((item) => {
            item.removeAttribute("disabled");
          });
      });
    },

    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 图片上传成功（改造多图处理）
    handleSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.photoFile.push(response.fileName); // 存入文件名数组
        this.previewImageList = fileList; // 更新回显列表
        this.form.inspectionimageurl = this.photoFile.join(","); // 拼接为逗号分隔字符串
      }
    },

    // 图片移除（核心修复：处理两种场景的图片删除）
    handleRemove(file, fileList) {
      // 场景1：上传成功的图片（有response属性）
      // 场景2：编辑回显的图片（已在edit/detail方法中手动添加response属性）
      const fileName = file.response?.fileName;

      if (fileName) {
        // 从文件名数组中移除当前图片
        this.photoFile = this.photoFile.filter((item) => item !== fileName);
      } else {
        // 异常情况处理：如果没有fileName，通过url提取
        const url = file.url;
        if (url) {
          const extractFileName = url.replace(this.baseUrl + "/", "");
          this.photoFile = this.photoFile.filter(
            (item) => item !== extractFileName
          );
        }
      }

      this.previewImageList = fileList; // 更新回显列表
      this.form.inspectionimageurl = this.photoFile.join(","); // 重新拼接字符串

      // 调试用（可删除）：查看删除后的文件名数组
      console.log("删除后的图片数组：", this.photoFile);
    },

    // 上传前校验（保持单张校验逻辑）
    beforeUpload(file) {
      const isImage =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif" ||
        file.type === "image/jpg";
      const isLt500k = file.size / 1024 < 500;

      if (!isImage) {
        this.$message.error("上传图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt500k) {
        this.$message.error("上传图片大小不能超过 500KB!");
      }
      return isImage && isLt500k;
    },

    // 提交表单（改造多图参数提交）
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 构造提交参数：图片参数拼接为逗号分隔字符串
          const params = {
            id: this.form.id,
            drinksourceid: this.form.drinksourceid,
            inspectiontime: this.form.inspectiontime
              ? this.formatDate(this.form.inspectiontime)
              : "",
            countycode: this.form.countycode || "",
            address: this.form.address || "",
            inspectionnote: this.form.inspectionnote,
            inspectionimageurl: this.photoFile.join(","), // 关键：数组转逗号分隔字符串
          };

          if (this.form.id) {
            // 编辑操作
            updatePatrolRecord(params).then((response) => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增操作
            addPatrolRecord(params).then((response) => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    // 导出操作
    handleExport() {
      window.location.href = `/api/drinkingwater/export?drinksourceid=${this.queryParams.drinksourceid}&patrolTime=${this.queryParams.patrolTime}`;
    },

    // 日期格式化（转为YYYY-MM-DD）
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
  },
};
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

img {
  vertical-align: middle;
}

#panel {
  padding-bottom: 40px;
  min-height: calc(100% - 20px);
  margin: 0;

  // 分页样式
  .pagination-self {
    margin: 20px 0;
    display: flex;
    justify-content: flex-end;
    position: relative;

    .el-pagination__total {
      position: absolute;
      left: 5px;
      color: #409eff;
      font-weight: 600;
      font-size: 15px;
    }
  }

  // 刷新按钮样式
  .refresh-button {
    .el-icon-refresh {
      font-size: 18px;
      line-height: 28px;
    }
  }

  .el-card {
    margin: 10px;
  }

  // 查询表单样式
  .queryForm .el-card__body {
    padding: 0 20px !important;
  }

  .queryForm {
    .el-form-item {
      margin: 10px 0 10px 20px;
    }

    .el-form-item:first-child {
      margin-left: 0 !important;
    }

    .el-form-item__label {
      padding-right: 5px;
      color: #555;
    }

    .el-form-item__content {
      min-width: 200px;
    }
  }

  // 页面内容区样式
  .pageContent {
    .mb8 {
      margin-bottom: 8px;
    }

    .el-table {
      width: 100%;
    }

    .el-table-column {
      text-align: center;
    }
  }

  // 弹出层图片上传样式
  .el-upload--picture-card {
    width: 100px;
    height: 100px;
    margin-right: 10px;
  }

  // 核心修改：禁用状态下的上传组件样式优化
  ::v-deep .el-upload--disabled {
    // 禁用时隐藏删除按钮和新增图标
    .el-upload-list__item-delete {
      display: none !important;
    }
    // 禁用时保持图片预览样式一致
    .el-upload-list__item {
      opacity: 0.9;
    }
    // 禁用时隐藏上传按钮的边框hover效果
    .el-upload__input {
      display: none;
    }
  }

  // 修复图片变形问题：保持图片比例
  ::v-deep .el-upload-list__item-image {
    object-fit: contain !important;
    max-width: 100%;
    max-height: 100%;
  }

  // 详情/编辑模式禁用样式统一
  ::v-deep .el-select[disabled],
  ::v-deep .el-date-picker[disabled],
  ::v-deep .el-input[disabled],
  ::v-deep .el-textarea[disabled] {
    opacity: 0.9;
    cursor: not-allowed;
    background-color: #f9f9f9;
  }

  // 图片预览弹窗样式优化
  ::v-deep .el-image-viewer__wrapper {
    z-index: 9999 !important;
  }

  // 弹窗图片容器，确保大图片自适应显示
  .dialog-img-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 300px;
    padding: 20px;
    background-color: #f8f8f8;
    border-radius: 4px;
  }

  // 弹窗图片样式：保持比例，最大宽度和高度限制
  .dialog-img {
    max-width: 100%;
    max-height: 80vh; // 最大高度为视口高度的80%，避免超出屏幕
    object-fit: contain;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
}
</style>
